package com.tbl.modules.wms2.controller.operation;

import com.baomidou.mybatisplus.plugins.Page;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.service.interfacelog.InterfaceLogService;
import com.tbl.modules.wms2.dao.operation.QualityInfoDAO;
import com.tbl.modules.wms2.dao.operation.YclInOutFlowDao;
import com.tbl.modules.wms2.dao.ordermanage.asn.AsnHeaderDAO;
import com.tbl.modules.wms2.dao.ordermanage.delivery.DeliveryDao;
import com.tbl.modules.wms2.dao.purchasein.PurchaseOrderDAO;
import com.tbl.modules.wms2.dao.workorder.WorkOrderDAO;
import com.tbl.modules.wms2.entity.insidewarehouse.check.YclCheckEntity;
import com.tbl.modules.wms2.entity.operation.QualityInfoEntity;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnLineEntity;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderEntity;
import com.tbl.modules.wms2.service.operation.QualityInfoService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.ordermanage.asn.AsnLineService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购入库管理-质检录入
 *
 * @author DASH
 */
@Controller()
@RequestMapping(value = "/ycl/purchaseIn/qualityControl")
public class QualityControlController extends AbstractController {


    @Autowired
    private RoleService roleService;


    @Autowired
    private QualityInfoService qualityInfoService;
    @Resource
    private QualityInfoDAO qualityInfoDAO;
    @Resource
    private DeliveryDao deliveryDao;
    @Autowired
    private InterfaceLogService interfaceLogService;

    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(QualityInfoEntity qualityInfoEntity) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean result = qualityInfoService.insertOrUpdate(qualityInfoEntity);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "保存成功" : "保存失败");
        return resultMap;
    }


    /**
     * 新增一条待质检记录
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/createQcInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createQcInfo(DeliveryEntity entity) {
        Map<String, Object> resultMap = new HashMap<>();
        //创建一条质检信息,并发送待质检信息

        QualityInfoEntity qualityInfoEntity = qualityInfoService.insertQcInfo(entity.getDeliveryNo(), entity.getDeliveryLineNo(), entity.getMaterialCode(), entity.getLotsNum(), entity.getAsnNumber());
        //发送待质检信息
        if (qualityInfoEntity != null) {

            String qInfoId = qualityInfoEntity.getId();
            String type = "Y";//待质检传'Y',撤回传'N'
            String entityId = entity.getEntityId();
            String poNumber = entity.getPoCode();
            String poLineNumber = entity.getPoLineNum();
            String lotsNum = entity.getLotsNum();
            String materialCode = entity.getMaterialCode();
            BigDecimal quantity = entity.getReceiveQuantity();

            Map<String, Object> map = new HashMap<>();
            //调用EBS存储过程，发送待质检信息
            map = qualityInfoService.qcInfoToEBSProcessing(type, qInfoId, entityId, lotsNum, materialCode, poNumber, poLineNumber, quantity);
            if (map != null && map.containsKey("retcode")) {
                String retcode = String.valueOf(map.get("retcode"));
                String errbuf = String.valueOf(map.get("errbuf"));
                if ("S".equals(retcode)) {//发送返回成功
                    interfaceLogService.insertLog("cux_wip_wms2_int_fewms202_pkg.main", "qcInfoToEBSProcessing",
                            "qInfoId=" + qInfoId, retcode, "", errbuf);
                    QualityInfoEntity qua = new QualityInfoEntity();
                    qua.setId(qualityInfoEntity.getId());
                    qua.setSampleNo(errbuf);//报验单号
                    qua.setTobeQc("1");//已发送待质检
                    int num1 = qualityInfoDAO.updateById(qua);
                    resultMap.put("result", num1 == 1);
                    resultMap.put("msg", "成功发送待质检信息");
                } else if ("E".equals(retcode)) {
                    resultMap.put("result", false);
                    resultMap.put("msg", errbuf);
                }
            } else {
                resultMap.put("result", false);
                resultMap.put("msg", "发送待质检无响应");
            }

        }

        return resultMap;
    }


    @RequestMapping(value = "/updatePassWms", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public Map<String, Object> updatePassWms(@RequestParam("id") String id, @RequestParam("passWms") String passWms) {
        Map<String, Object> resultMap = new HashMap<>();

        //在质检表中保存质检员通过WMS输入的质检结果
        String name = getSessionUser().getName();//质检员姓名
        String username = getSessionUser().getUsername();//质检员工号
        QualityInfoEntity qualityInfoEntity = new QualityInfoEntity();
        qualityInfoEntity.setId(id);
        qualityInfoEntity.setPassWms(passWms);
        qualityInfoEntity.setIntoInventoryBy("3");
        qualityInfoEntity.setUsername(username);
        qualityInfoEntity.setName(name);
        boolean b = qualityInfoService.updateById(qualityInfoEntity);
        if ("3".equals(passWms)) {
            resultMap.put("result", false);
            resultMap.put("msg", "质检不合格");
            return resultMap;
        }
        /**
         * 先查询该收货单物料是否在上下架流水表，如果已经上架，则更新接收单的isPass,并对上下架流水表数据进行入库.
         * 如果未上架，只需要更改接收单为允许入库状态，接收单数据在上下架时判断isPass是否为1，则自动入库
         */
        if (b) {
            QualityInfoEntity qua = qualityInfoService.selectQualityInfoById(id);
            //更新接收单数据
            boolean bUpdate = qualityInfoService.updateQcStateForDelivery(qua.getDeliveryNo(), qua.getDeliveryLineNo());
            if (bUpdate) {
                resultMap.put("result", true);
                resultMap.put("msg", "操作成功");
                return resultMap;
            }
        }
        resultMap.put("result", false);
        resultMap.put("msg", "操作失败");
        return resultMap;
    }


    /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        //mv.addObject("operationCode", roleService.selectOperationByRoleId(2L, MenuConstant.warehouselist));
        mv.setViewName("techbloom2/purchaseIn/qualitycontrol/list");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list() {
        Map<String, Object> paramsMap = getAllParameter();
        if (paramsMap.containsKey("createTime") && StringUtils.isNotEmpty(String.valueOf(paramsMap.get("createTime")))) {//2020-07-01+~+2020-08-01
            String createTime = String.valueOf(paramsMap.get("createTime"));
            String createTimeStart = createTime.substring(0, 10);
            String createTimeEnd = createTime.substring(createTime.lastIndexOf("-") - 7);
            paramsMap.put("createTimeStart", createTimeStart);
            paramsMap.put("createTimeEnd", createTimeEnd);
        }
        Map<String, Object> resultMap = new HashMap<>(4);
        int count = qualityInfoDAO.count(paramsMap);
        if (count > 0) {
            List<QualityInfoEntity> list = qualityInfoService.getQualityInfoList(paramsMap);
            resultMap.put("code", 0);
            resultMap.put("msg", null);
            resultMap.put("count", count);
            resultMap.put("data", list);
            return resultMap;
        }
        return restfulResponseError();
    }

    /**
     * 跳转编辑页
     *
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toDetail(String id) {
        ModelAndView mv = this.getModelAndView();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        List<QualityInfoEntity> list = qualityInfoService.getQualityInfoList(map);
        mv.addObject("data", list.get(0));
        mv.setViewName("techbloom2/purchaseIn/qualitycontrol/edit");
        return mv;
    }


}
